package com.haircut.sys.utils.dept;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.RadixUtil;
import cn.hutool.core.util.StrUtil;
import com.haircut.sys.model.dept.SysDept;
import com.haircut.sys.vo.dept.DeptTreeVo;
import com.modular.constant.NumberConstant;

import java.util.*;
import java.util.stream.Collectors;

public class DeptUtils {
    /**
     *
     * @param deptLevel
     * @return
     */
    public static Integer calcDeptLevel(Integer deptLevel){
        deptLevel = Optional.ofNullable(deptLevel).orElse(NumberConstant.ZERO);
        deptLevel ++;
        return deptLevel;
    }

    public static String coverHierarchy(String currId,String hierarchy){

        return StrUtil.format("{}/{}",hierarchy, RadixUtil.encode(RadixUtil.RADIXS_59,Long.parseLong(currId)));
    }

    public static List<DeptTreeVo> coverTree(List<SysDept> deptList,String parentId){
        if(CollUtil.isEmpty(deptList)){
            return Collections.emptyList();
        }
        Map<String,List<SysDept>> deptpMap =deptList.stream().collect(Collectors.groupingBy(SysDept::getParentId));
        return coverTree(deptpMap,parentId);
    }

    /**
     * 将部门该为前端的列表
     * @param deptpMap
     * @param parentId
     * @return
     */
    private static List<DeptTreeVo> coverTree( Map<String,List<SysDept>> deptpMap,String parentId){
        List<SysDept> itemList = deptpMap.get(parentId);
        if(CollUtil.isEmpty(itemList)){
            return Collections.emptyList();
        }
        List<DeptTreeVo> treeVoList = new ArrayList<>(itemList.size());
        DeptTreeVo treeVo = null;
        for(SysDept dept:itemList){
            treeVo = new DeptTreeVo();
            treeVo.setId(dept.getId());
            treeVo.setLabel(dept.getDeptName());
            treeVo.setChildren(coverTree(deptpMap,dept.getId()));
            treeVoList.add(treeVo);
        }
        return treeVoList;
    }


}
